package cn.jiyun.service.impl;

import cn.jiyun.commons.StringUtil;
import cn.jiyun.dao.domain.Role;
import cn.jiyun.dao.domain.User;
import cn.jiyun.dao.mapper.RoleMapper;
import cn.jiyun.dao.mapper.UserMapper;
import cn.jiyun.service.RoleService;
import cn.jiyun.commons.vo.BootstrapTableData;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserMapper userMapper;


    @Override
    public Role findRole(Integer roleid) {
        return roleMapper.selectByPrimaryKey(roleid);
    }

    @Override
    public BootstrapTableData getPaginatedRoleList(String rolename, String ordername, String order, Integer offset, Integer limit) {
        //设置分页条件
        PageHelper.offsetPage(offset, limit);
        //设置查询条件
        Example example = new Example(Role.class);
        Example.Criteria criteria = example.createCriteria();
        Example.OrderBy orderByObj;
        if (!StringUtil.isEmpty(rolename)) {
            criteria.andLike("roleName", "%" + rolename.trim() + "%");
        }
        //设置排序条件
        orderByObj = example.orderBy(ordername.trim());
        if (!StringUtil.isEmpty(order)) {
            if ("desc".equals(order.trim())) {
                orderByObj.desc();
            } else {
                orderByObj.asc();
            }
        }
        List<Role> roles = roleMapper.selectByExample(example);
        PageInfo<Role> pageInfo = new PageInfo<>(roles);
        BootstrapTableData tableData = new BootstrapTableData();
        tableData.setTotal(pageInfo.getTotal());
        tableData.setRows(pageInfo.getList());
        return tableData;
    }

    @Override
    public boolean saveRole(Role role) throws Exception {
        Example example = new Example(Role.class);
        example.createCriteria().andEqualTo("roleName", role.getRoleName());
        // 查询数据库中具有相同角色名称的记录数目
        int rowCount = roleMapper.selectCountByExample(example);
        // 如果没有相同角色名称的记录，则执行角色的添加
        if (rowCount == 0) {
            // 新增成功，rowCount的值应该是1
            role.setUpdateTime(new Date());
            role.setCreateTime(new Date());
            rowCount = roleMapper.insert(role);
        } else {
            // 否则抛异常
            throw new RuntimeException("角色名称已存在");
        }
        // rowCount的值为1表示新增成功
        return rowCount == 1;
    }

    @Transactional
    @Override
    public boolean updateRole(Role role) {
        Example example = new Example(Role.class);
        example.createCriteria().andEqualTo("roleName", role.getRoleName());
        // 查询数据库中具有相同角色名称的记录数目
        int rowCount = roleMapper.selectCountByExample(example);
        // 如果没有相同角色名称的记录，则执行角色的添加
        if (rowCount > 0) {
            throw new RuntimeException("角色名称已存在");

        }
        role.setUpdateTime(new Date());
        int result = roleMapper.updateByPrimaryKeySelective(role);
        return result == 1;
    }


    @Transactional
    @Override
    public boolean deleteRole(List<Integer> roleids) throws Exception {
        Example example = new Example(User.class);
        for (int i = 0; i < roleids.size(); i++) {
            example.createCriteria().andEqualTo("roleId", roleids.get(i));
            List<User> users = userMapper.selectByExample(example);
            if (users != null && users.size() > 0) {
                throw new Exception("角色id:" + i + " 下面有用户，不能删除");
            }
        }
        Example roleExample = new Example(Role.class);
        roleExample.createCriteria().andIn("id", roleids);
        int rowCount = roleMapper.deleteByExample(roleExample);
        if (rowCount != roleids.size()) {
            // 如果删除的记录条目数与要删除的条目数不一致，则不删除，使用下属语句回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            // 返回false表示删除失败
            return false;
        }
        return true;
    }


}
